import { getImportedPF } from "@/api/data";

export default {
    state: {
        // 模型信息
        result: {},
    },
    mutations: {
        // 获取模型信息
        getResult(state, val) {
            state.result = val;

            // 先删除原先的数据库
            var deleteRequest = window.indexedDB.deleteDatabase('myDatabase');
            deleteRequest.onerror = function (event) {
                console.log("删除数据库失败");
            };
            deleteRequest.onsuccess = function (event) {
                console.log("删除数据库成功");

                // 删除成功后新建数据库
                var request = indexedDB.open('myDatabase', 1);
                request.onupgradeneeded = function (event) {
                    console.log('创建对象存储空间');
                    var db = event.target.result;

                    // 创建一个名为 'results' 的对象存储空间
                    var store = db.createObjectStore('results', { autoIncrement: true });

                    // 存储每个对象到 IndexedDB
                    if (val === null || val === undefined) {
                        val = {};
                    }

                    Object.keys(val).forEach(key => {
                        var data = { key: key, value: val[key] };
                        store.put(data);
                    });
                };

                request.onsuccess = function (event) {
                    console.log('打开数据库成功');
                    var db = event.target.result;
                    db.close();
                    console.log("数据库已关闭");
                };

                request.onerror = function (event) {
                    console.error('打开数据库失败');
                };
            };
        },
        // 在页面加载时从 IndexedDB 中获取模型信息
        initResult(state) {
            console.log("result初始化")

            var request = indexedDB.open('myDatabase', 1);

            request.onsuccess = function (event) {
                var db = event.target.result;
                if (db.objectStoreNames.contains('results')) {
                    var transaction = db.transaction(['results'], 'readonly');
                    var objectStore = transaction.objectStore('results');

                    var getRequest = objectStore.getAll();

                    getRequest.onsuccess = function (event) {
                        var data = event.target.result;
                        var result = {};

                        data.forEach(item => {
                            result[item.key] = item.value;
                        });

                        state.result = result;
                        console.log(state.result);

                        db.close();
                        console.log('数据库已关闭')
                    };
                }
            };

            request.onerror = function (event) {
                console.error('Error opening IndexedDB:', event.target.error);
            };
        },
    }
}